import java.io.*;
import java.net.*;
import java.util.*;

//Na mesma maquina
//Colocar 2 possibildades, por ip e na mesma maquina

public class UDPPingerServer {
    private static final double LOSS_RATE = 0.3;
    private static final int AVERAGE_DELAY = 100; //usado para testar no mesmo pc, os 2
    public static void main ( String args[] ) throws Exception
    {
        Random random = new Random();
        DatagramSocket serverSocket = new DatagramSocket(1234);
        byte[] receiveData;
        byte[] sendData;
        DatagramPacket receivePacket;
        DatagramPacket sendPacket;
        String mensagem;
        int porta;
        InetAddress IPAddress;
        while(true)
        {
            receiveData = new byte[44];
            sendData = new byte[44];
            receivePacket = new DatagramPacket(receiveData, receiveData.length);
            serverSocket.receive(receivePacket);
            mensagem = new String(receivePacket.getData());
            System.out.println(mensagem);
            if(random.nextDouble() >  LOSS_RATE)
            {
                sendData = receiveData;
                IPAddress = receivePacket.getAddress();
                porta = receivePacket.getPort();
                sendPacket = new DatagramPacket(sendData, sendData.length, IPAddress, porta);
                Thread.sleep((AVERAGE_DELAY * (Math.abs(random.nextLong()) % 3) + 100));
                serverSocket.send(sendPacket);
            }

        }
    }

}
